import json
import requests
import sys
from lxml import etree


# 下载地址
class EightZeroSpider:
    def __init__(self, num):
        self.num = num
        self.url = "http://www.i80s.cc/hddown/{}.html".format(num)
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"}

    def parse_url(self, url):
        resp = requests.get(url, headers=self.headers, verify=False)
        return resp.content.decode()

    def get_content_list(self, html_str):
        content_list = []
        html = etree.HTML(html_str)
        name = html.xpath("//meta[@name='keywords']/@content")[0]
        name = (name.split(',')[0]).strip().replace('/', '')
        ul = html.xpath("//ul[@class='downlist']")[0]
        li_list = ul.xpath(".//li")

        for li in li_list:
            download_url = li.xpath(".//span[@class='downlink']/a/@href")
            download_url = download_url[0] if len(download_url) > 0 else None
            content_list.append(download_url)
        return name, content_list

    def save_content_list(self, name, content_list):
        with open(name + '.txt', 'w', encoding='utf-8') as f:
            f.write('ID：' + str(self.num) + '\n')
            for content in content_list:
                f.write(json.dumps(content, ensure_ascii=False, indent=2).replace("\"", ''))
                f.write('\n')

    def run(self):
        url = self.url
        html_str = self.parse_url(url)
        try:
            name, content_list = self.get_content_list(html_str)
            self.save_content_list(name, content_list)
            print('写入完毕')
        except:
            print('不存在')


if __name__ == '__main__':
    name = sys.argv[1]
    eight_zero = EightZeroSpider(name)
    eight_zero.run()
